﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KCMS.Models;
using System.Web.Script.Serialization;
using KCMS.BusinessLogic.Interfaces;
using StructureMap;
using KCMS.BusinessLogic.Models;
using AutoMapper;
using KCMS.Web.Models;

namespace KCMS.Controllers
{
    public class CartController : Controller
    {

        private ICartService cartService = ObjectFactory.GetInstance<ICartService>();
        private IOrderService orderService = ObjectFactory.GetInstance<IOrderService>();
        private IOrderDeliveryService orderDeliveryService = ObjectFactory.GetInstance<IOrderDeliveryService>();
        private IOrderStatusService orderStatusService = ObjectFactory.GetInstance<IOrderStatusService>();
        private IOrderItemService orderItemService = ObjectFactory.GetInstance<IOrderItemService>();
        private IClientService clientService = ObjectFactory.GetInstance<IClientService>();
        private ICalculator calculator = ObjectFactory.GetInstance<ICalculator>();
        private IMailService mail = ObjectFactory.GetInstance<IMailService>();
        private ISettingsService settingsService = ObjectFactory.GetInstance<ISettingsService>();
        [HttpPost]
        public ActionResult ShowDetails(CartItem[] items)
        {
            var model = cartService.BuildFullModel(items);
            return PartialView(model);
        }
        [HttpPost]
        public JsonResult Total(CartItem[] items)
        {
            
            string total = calculator.getTotal(items).ToString() + " руб.";
            return Json(new { total = total }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Show()
        {
            return View();
        }
        [HttpGet]
        public ActionResult CreateClient()
        {
            Client client = new Client();
            var model=Mapper.Map<BusinessLogic.Models.Client, KCMS.Web.Models.ClientViewModel>(client);
            return PartialView(model);
        }
        [HttpPost]
        public ActionResult CreateClient(ClientViewModel model)
        {
            return RedirectToAction("CreateOrder");
        }
        [HttpGet]
        public ActionResult ChooseDelivery()
        {
            IEnumerable<OrderDelivery> deliveries = orderDeliveryService.getAll();
            var model = Mapper.Map<IEnumerable<BusinessLogic.Models.OrderDelivery>, IEnumerable<KCMS.Web.Models.OrderDeliveryViewModel>>(deliveries);
            return PartialView(model);
        }
        [HttpPost]
        public ActionResult ShowClientDetails(ClientViewModel client)
        {
            return PartialView(client);
        }

        [HttpGet]
        public ActionResult CreateOrder()
        {
            return PartialView();
        }
        [HttpPost]
        public JsonResult CreateOrder(CartItem[] items,ClientViewModel client,Guid deliveryId)
        {
            try
            {
                Order order = new Order();
                order.OrderDeliveryId = deliveryId;
                order.Total = calculator.getTotal(items);
                Settings settings=settingsService.getSettings();
                if (!orderService.ChekOrderTotal(order))
                {
                    return Json(new { check = false, message = "Минимальная сумма заказа "
                        +settings.SaleMinimum.ToString()+" руб.!" }, JsonRequestBehavior.AllowGet);
                }
                order.ClientId=clientService.save(Mapper.Map<KCMS.Web.Models.ClientViewModel,BusinessLogic.Models.Client>(client));               
                
                Guid orderId=orderService.save(order);
                OrderStatus status = new OrderStatus();
                
                status.OrderId = orderId;
                status.Status = Status.New.ToString();
                orderStatusService.save(status);

                Order savedOrder = orderService.getById(orderId);
                IEnumerable<OrderItem> orderItems =cartService.ConvertToOrderItems(items,savedOrder);
                foreach (var item in orderItems)
                {
                    orderItemService.save(item);
                }
                mail.SendMail(
                    "Интернет магазин Wake-up",
                    "administrator@wakeup-shop.ru",
                    client.Email,
                    "Заказ №" + savedOrder.Number.ToString(),
                    "Вашему заказу №"+savedOrder.Number.ToString()+" присвоен статус новый. В ближайшее время с Вами свяжутся наши менеджеры.");
                return Json(new { check = true, message = "Ваш заказ добавлен на обработку,скоро с Вами свяжутся наши менеджеры." }, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(new { check = false, message = "Приносим свои извенения,заказ не может быть оформлен." }, JsonRequestBehavior.AllowGet);
            }
        }
        [HttpPost]
        public ActionResult ShowOrderDetails(CartItem[] items)
        {
            var model = cartService.BuildFullModel(items);
         
            return PartialView(model);
        }
        [Authorize]
        [HttpGet]
        public ActionResult AddToOrderByAdmin()
        {
            return PartialView();
        }
        [Authorize]
        [HttpPost]
        public JsonResult AddToOrderByAdmin(CartItem[] items, int number)
        {
            try
            {
                Order order = orderService.getByNumber(number);
                Settings settings = settingsService.getSettings();
                IEnumerable<OrderItem> orderItems = cartService.ConvertToOrderItems(items,order);
                foreach (var item in orderItems)
                {
                    orderItemService.save(item);
                }
                return Json(new { check = true, message = "Добавление успешно завершено!" }, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(new { check = false, message = "Проблемы с добавлением!" }, JsonRequestBehavior.AllowGet);
            }
        }

    }
}
